﻿using Combination.Client.Core;
using Combination.Core;
using Combination.UI;
using Microsoft.Extensions.DependencyInjection;
using System.Threading;
using System;
using System.Windows;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Linq;
using System.Windows.Threading;
using System.Runtime.InteropServices;
using Microsoft.Extensions.Configuration;

namespace Combination.Client
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        #region 成员变量
        private static Mutex _mutex;

        ///<summary>
        /// 该函数设置由不同线程产生的窗口的显示状态
        /// </summary>
        /// <param name="hWnd">窗口句柄</param>
        /// <param name="cmdShow">指定窗口如何显示。查看允许值列表，请查阅ShowWlndow函数的说明部分</param>
        /// <returns>如果函数原来可见，返回值为非零；如果函数原来被隐藏，返回值为零</returns>
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);

        /// <summary>
        ///  该函数将创建指定窗口的线程设置到前台，并且激活该窗口。键盘输入转向该窗口，并为用户改各种可视的记号。
        ///  系统给创建前台窗口的线程分配的权限稍高于其他线程。 
        /// </summary>
        /// <param name="hWnd">将被激活并被调入前台的窗口句柄</param>
        /// <returns>如果窗口设入了前台，返回值为非零；如果窗口未被设入前台，返回值为零</returns>
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        #endregion
        private static IHost _host;

        public static MainWindowVm MainWindowVm
        {
            get
            {
                if (NUI.IsInDesignMode)
                {
                    return new MainWindowVm();
                }
                else
                {
                    return _host.Services.GetService<MainWindowVm>();
                }
            }
        }

        public static IHost Host => _host;

        public static IHelper Helper => _host.Services.GetRequiredService<IHelper>();

        public static IDataContext LocalData => _host.Services.GetRequiredService<IDataContext>();
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
                 
            bool createdNew = false;
            _mutex = new Mutex(true, "Combination.Client", out createdNew);
            if (!createdNew)
            {
                //MessageBox.Show("程序已启动！", "系统提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                var process = Process.GetProcessesByName("Combination.Client");
                var firstProcess = process.FirstOrDefault(p => p.Handle != Process.GetCurrentProcess().Handle);
                if (firstProcess != null)
                {
                    ShowWindowAsync(firstProcess.MainWindowHandle, 9);//显示
                    SetForegroundWindow(firstProcess.MainWindowHandle);//最前端
                }
                this.Shutdown();
            }
            //UI线程未捕获异常处理事件
            this.DispatcherUnhandledException += App_DispatcherUnhandledException;
            //Task线程内未捕获异常处理事件
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
            //非UI线程未捕获异常处理事件
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            _host = new BasicHost();
            _host.Init();
            Current.MainWindow = new MainWindow();
            Current.MainWindow.ShowDialog();
            Current.Shutdown();
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                MessageBox.Show($"{e.ExceptionObject}", "系统异常");
            }
            catch { }
        }

        private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            try
            {
                e.SetObserved();
                MessageBox.Show($"{e.Exception}", "系统异常");
            }
            catch { }
        }

        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            try
            {
                e.Handled = true;
                MessageBox.Show($"{e.Exception}", "系统异常");
            }
            catch { }
        }
    }
}
